package cn.hjh.service;

import cn.hjh.dao.DeptDao;
import cn.hjh.dao.EmpDao;
import cn.hjh.dao.HibernateUtil;
import cn.hjh.pojo.Dept;
import cn.hjh.pojo.Emp;
import cn.hjh.pojo.EmpCondition;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class EmpBiz {
	private EmpDao dao = new EmpDao();
	
	public void addNewEmp(Emp emp){
		Transaction tx = null;
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			dao.save(emp);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null)
				tx.rollback();
		}
	}

	public List<Emp> findEmpsByDept(Dept dept){
		Transaction tx = null;
		List<Emp> result =null;
		try {
			tx = dao.currentSession().beginTransaction();
			result = dao.findByDept(dept);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null)
				tx.rollback();
		}
		return result;
	}

	public List<Emp> findAllEmps(){
		Transaction tx = null;
		List<Emp> result =null;
		try {
			tx = dao.currentSession().beginTransaction();
			result = dao.findAll();
			for (Emp emp:result) {
				System.out.println("员工姓名："+emp.getEmpName());
				System.out.println("所在部门:"+emp.getDept().getDname());
			}
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return result;
	}

	public void changeDept(Integer empNo,Integer deptno){
		Transaction tx = null;
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			Dept dept = new DeptDao().load(deptno);
			Emp emp = dao.load(empNo);
			emp.setDept(dept);
			dept.getEmps().add(emp);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null)
				tx.rollback();
		}
	}

	public void shili17(){
		Transaction tx = null;
		try {
			tx = HibernateUtil.currentSession().beginTransaction();
			Emp emp = (Emp) dao.currentSession().get(Emp.class,7839);
			Dept dept = emp.getDept();
			dept.getDeptname();
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null)
				tx.rollback();
		}
	}
}
